package com.funcas.pcloud.security.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.funcas.pcloud.common.exception.ServiceException;
import com.funcas.pcloud.security.entity.BaseUserDetail;
import com.funcas.pcloud.security.entity.UserVO;
import com.funcas.pcloud.security.mapper.UserMapper;
import com.funcas.pcloud.security.service.IUserService;
import com.google.common.collect.Sets;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author funcas
 * @version 1.0
 * @date 2018年10月18日
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private IUserService userService;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {

        UserVO userVO = userService.findUserByLoginName(name);
        if(userVO == null) {
            throw new ServiceException("用户不存在");
        }


        Set<GrantedAuthority> grantedAuthorities = userService.findUserPermissions(userVO.getId());
        // 可用性 :true:可用 false:不可用
        boolean enabled = userVO.getState() == 1;

        User user = new User(userVO.getUsername(), userVO.getPassword() ,enabled,true,
                true,true, grantedAuthorities);
        return new BaseUserDetail(userVO, user);
    }
}
